﻿using System;
using System.Windows.Forms;
using FoundationClass.Entity;
using Telerik.WinControls.UI;

namespace P2MARY_INTERNET.Controls
{
    public partial class PromotionDialog : Form
    {
        public PromotionDialog()
        {
            InitializeComponent();
        }

        public Promotion Promotion;

        private void btnOK_Click(object sender, EventArgs e)
        {
            if(txtProName.Text.Trim().Length == 0)
            {
                lblValidate.Text = @"กรูณากรอกชื่อโปรโมชั่น";
                return;
            }
            
            Promotion = new Promotion
            {
                Name = txtProName.Text,
                StartDate = radStartDate.Value,
                EndDate = radEndDate.Value,
                
                //StartTime = radStartTime.Value,
                //EndTime = radEndTime.Value,
                Detail = txtDetail.Text,
                PriceRate = double.Parse(txtPriceRate.Value.ToString()),
                FixHour = int.Parse(txtFixHour.Text),
                Type = drpPromotionType.SelectedIndex,
                IsTotal = chkIsTotal.IsChecked
            };
            if(!chkTime.IsChecked)
            {
                Promotion.StartTime = Promotion.EndTime = DateTime.Parse("1/1/1753 12:00:00 AM");
            }
            else
            {
                Promotion.StartTime = GetTimeFromDropdown(drpStartTime);
                Promotion.EndTime = GetTimeFromDropdown(drpEndTime);
            }
            DialogResult = DialogResult.OK;
        }

        private DateTime GetTimeFromDropdown(RadDropDownList drp)
        {
            int time = int.Parse(drp.Text.Substring(0, 2));
            return new DateTime(2000, 1, 1, time, 0, 0);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private void chkTime_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            grpTime.Enabled = chkTime.IsChecked;
        }

        private void drpStartTime_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            CalculateTime();
        }

        private void drpEndTime_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            CalculateTime();
        }

        private void CalculateTime()
        {
            int start = int.Parse(drpStartTime.Text.Substring(0, 2));
            int end = int.Parse(drpEndTime.Text.Substring(0, 2));
            int result;
            if (start > end)
            {
                result = 24 - start + end;
            }
            else
            {
                result = end - start;
            }
            txtFixHour.Value = result;
        }
    }
}
